import {ELType} from "./ELType";

export default class ELNode {
    id: string;
    type: ELType;
    aliasId: string;
    name: string;
    data: string;
    tag: string;
    nodeId: string;
    child: ELNode[];

    //loop专用
    startNode: ELNode;
    breakNode: ELNode;
    startNum: number;

    constructor(id: string = "") {
        if (id) this.id = id
        this.child = []
    }

    public addChild(elNode: ELNode) {
        this.child.push(elNode);
    }

    private assert(condition: boolean, msg: string = "") {
        if (!condition) throw new Error(msg);
    }

    public getElString() {
        if (this.type === ELType.ID) return this.nodeId;


        const type = this.type;
        const children = this.child;
        const joins = this.child.map(item => item.getElString()).join(",");
        switch (type) {
            case ELType.IF:
                debugger;
                if (children.length === 1) return `IF(${this.nodeId},${joins})`;
                return `IF(${this.nodeId},${joins})`;
            case ELType.LOOP:
                const name = this.name.toUpperCase();
                const breakStr = !!this.breakNode ? `.BREAK(${this.breakNode.nodeId})` : ""
                const startStr = (this.startNum > 0) ? this.startNum : this.startNode?.nodeId;
                if (children.length === 1) return `${name}(${startStr}).DO(${joins})${breakStr}`;
                else return `${name}(${startStr}).DO(WHEN(${joins}))${breakStr}`;
            case ELType.SWITCH:
                return `SWITCH(${this.nodeId}).to(${joins})`;
            default:
                if (children.length === 1) return joins;
                return `${this.type}(${joins})`
        }
    }
}